package com.example.rockscissorspapergame.service;


import com.example.rockscissorspapergame.Constants;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.*;

/**
 * 发起连接侧的代理
 */
public class RemoteProxy implements IRemoteBroker {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0x01008, "RemoteProxy");

    // RemoteObject 实例
    private final IRemoteObject remote;

    /**
     * 构造方法
     *
     * @param remote RemoteObject 实例
     */
    public RemoteProxy(IRemoteObject remote) {
        this.remote = remote;
    }

    @Override
    public IRemoteObject asObject() {
        return remote;
    }

    /**
     * 跨端发送消息
     *
     * @param message 要发送的消息
     */
    public void sendMessage(String message) {
        // 将消息封装到 MessageParcel 中
        MessageParcel data = MessageParcel.obtain();
        data.writeString(message);

        MessageParcel reply = MessageParcel.obtain();
        MessageOption option = new MessageOption(MessageOption.TF_SYNC);
        try {
            // 通过 RemoteObject 实例发送消息
            remote.sendRequest(IRemoteObject.MIN_TRANSACTION_ID, data, reply, option);
            // 获取消息传递结果
            int ec = reply.readInt();
            if (ec != Constants.ERR_OK) {
                throw new RemoteException();
            }
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "RemoteException: %{public}s", e.getMessage());
        }
    }
}
